import 'dart:math';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  tz.initializeTimeZones();
  await AndroidAlarmManager.initialize();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Duang',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  FlutterLocalNotificationsPlugin localNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  final String punchKey = 'punchInTime';
  Future<SharedPreferences>? prefsFuture;
  @override
  void initState() {
    super.initState();

    prefsFuture = SharedPreferences.getInstance();
    const android = AndroidInitializationSettings('@mipmap/ic_launcher');
    const initSettings = InitializationSettings(android: android);

    localNotificationsPlugin.initialize(initSettings);
    recordPunchInTime();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
          const Text('打卡记录'),
          Text(
            ' ${_formattedDate()}',
            style: const TextStyle(fontSize: 15.0),
          )
        ]),
      ),
      body: FutureBuilder(
        future: prefsFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            final prefs = snapshot.data as SharedPreferences;
            final keys = prefs.getKeys(); // 过滤出包含打卡记录的键，即日期格式的键
            final punchRecords =
                keys.where((String key) => key.contains('-')).toList();

            // 将键转换为日期和时间戳的对，并且按时间降序排列
            List<int> punchData = punchRecords.map((String key) {
              final int timestamp = prefs.getInt(key)!;
              return timestamp;
              /* print(timestamp);
                  final DateTime dateTime =
                      DateTime.fromMillisecondsSinceEpoch(timestamp);
                  // 手动构建格式化的日期时间字符串
                  final String formattedDateTime =
                      '${dateTime.year.toString().padLeft(4, '0')}-'
                      '${dateTime.month.toString().padLeft(2, '0')}-'
                      '${dateTime.day.toString().padLeft(2, '0')} '
                      '${dateTime.hour.toString().padLeft(2, '0')}:'
                      '${dateTime.minute.toString().padLeft(2, '0')}:'
                      '${dateTime.second.toString().padLeft(2, '0')}';
                  return formattedDateTime; */
            }).toList();

            punchData.sort((int a, int b) => b.compareTo(a));
            // 手动构建格式化的日期时间字符串
            /* punchData = punchData.map((int timestamp) {
              final DateTime dateTime =
            }) */
            return ListView.builder(
              itemCount: punchData.length,
              itemBuilder: (context, index) {
                return Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 16.0, vertical: 4.0),
                  child: Text(
                    formatTimestamp(punchData[index]),
                    style: const TextStyle(
                      height: 1.1,
                      fontSize: 15.0,
                    ),
                  ),
                );
              },
            );
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          reRecordPunchInTime();
        },
        backgroundColor: Colors.blueAccent,
        shape: const CircleBorder(),
        child: const Icon(Icons.replay_circle_filled_rounded),
      ),
    );
  }

  String formatTimestamp(int timestamp) {
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);

    // 使用Dart的内置功能来构建格式化的日期和时间字符串
    String year = dateTime.year.toString().padLeft(4, '0');
    String month = dateTime.month.toString().padLeft(2, '0');
    String day = dateTime.day.toString().padLeft(2, '0');
    String hour = dateTime.hour.toString().padLeft(2, '0');
    String minute = dateTime.minute.toString().padLeft(2, '0');
    String second = dateTime.second.toString().padLeft(2, '0');

    return "$year-$month-$day $hour:$minute:$second";
  }

  /// 记录打卡时间
  Future<void> recordPunchInTime() async {
    final prefs = await SharedPreferences.getInstance();
    final now = DateTime.now();
    final todayKey = '${now.year}-${now.month}-${now.day}';
    // 如果没有则设置今天的打卡时间
    if (!prefs.containsKey(todayKey)) {
      await prefs.setInt(todayKey, now.millisecondsSinceEpoch);
      scheduleNotificationForToday(now);
    }
  }

  /// 重新记录打卡时间
  Future<void> reRecordPunchInTime() async {
    final prefs = await SharedPreferences.getInstance();
    final now = DateTime.now();
    final todayKey = '${now.year}-${now.month}-${now.day}';
    await prefs.setInt(todayKey, now.millisecondsSinceEpoch);
    refreshPrefs();
    scheduleNotificationForToday(now);
  }

  void refreshPrefs() {
    setState(() {
      prefsFuture = SharedPreferences.getInstance();
    });
  }

  /// 设置警报

  void scheduleNotificationForToday(DateTime now) async {
    print('设置警报');
    final now = DateTime.now();
    // 使用当前时间的秒数与一个随机数相结合来生成警报ID
    final int alarmId = Random().nextInt(pow(2, 31).toInt()) + now.second;
    final nineHoursLater = now.add(Duration(hours: 9));
    // final nineHoursLater = now.add(const Duration(seconds: 3));
    await AndroidAlarmManager.oneShotAt(
      tz.TZDateTime.from(nineHoursLater, tz.local),
      alarmId,
      alarmCallback,
      exact: true,
      wakeup: true,
    );
  }

  /// 警报回调方法
  @pragma('vm:entry-point')
  static void alarmCallback() async {
    print('警报回调');
    final prefs = await SharedPreferences.getInstance();
    final now = DateTime.now();
    final todayKey = '${now.year}-${now.month}-${now.day}';
    if (prefs.containsKey(todayKey)) {
      showNotification();
    }
  }

  static void showNotification() async {
    var android = const AndroidNotificationDetails(
      'com.leggod.duang',
      '下班通知',
      channelDescription: '下班打卡提示',
      importance: Importance.max,
      priority: Priority.high,
      playSound: true,
      enableVibration: true,
    );
    var platform = NotificationDetails(android: android);
    var localNotificationsPlugin = FlutterLocalNotificationsPlugin();

    for (int i = 1; i <= 3; i++) {
      final now = DateTime.now();
      // 使用当前时间的秒数与一个随机数相结合来生成警报ID
      final int notificationId =
          Random().nextInt(pow(2, 31).toInt()) + now.second;
      await localNotificationsPlugin.show(
        notificationId,
        '下班啦~',
        '重要的事情说三遍',
        platform,
      );
    }
  }

  String _formattedDate() {
    DateTime now = DateTime.now();
    // 使用 padLeft 方法确保月和日始终是两位数字
    String month = now.month.toString().padLeft(2, '0');
    String day = now.day.toString().padLeft(2, '0');
    return '$month月$day日';
  }
}
